package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"post-release/models"
	"strconv"
)

func Add(c *gin.Context) {
	title := c.PostForm("title")
	comment := c.PostForm("comment")
	if title == "" || comment == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := models.Article{
		Title:   title,
		Comment: comment,
	}
	err := models.DB.Create(&data).Debug().Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func Photo(c *gin.Context) {
	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	dst := "./file" + file.Filename
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, dst)

	c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var article []models.Article
	models.DB.Offset(offset).Limit(size).Debug().Find(&article)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return
}
